package com.itcoon.cloud.framework.springdoc.plugin;/**
 * @author Athric Yu
 * 2024/11/11
 **/

import com.itcoon.cloud.framework.enums.BasicEnum;
import com.itcoon.cloud.framework.enums.ValueEnum;
import io.swagger.v3.core.util.PrimitiveType;
import io.swagger.v3.oas.models.media.ObjectSchema;
import io.swagger.v3.oas.models.media.Schema;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 *
 *
 * @author Athric Yu
 * 2024/11/11
 **/
public interface BasicEnumCustomizer<V extends Serializable, E extends Enum<E>> {

    default List<V> getValues(Class<ValueEnum<V, E>> enumType) {
        return Arrays.stream(enumType.getEnumConstants())
                .map(ValueEnum::value)
                .collect(Collectors.toList());
    }

    default String getDescription(Class<BasicEnum<V, E>> enumType){
        StringJoiner joiner = new StringJoiner(", ");
        for (BasicEnum<V, E> baseEnum : enumType.getEnumConstants()) {
            joiner.add(baseEnum.value() + "=" + baseEnum.description());
        }
        return "[" + joiner + "]";
    }


    default Schema<V> getSchema(Class<V> primitiveType, Schema<?> sourceSchema){
        Schema<Object> schema;
        PrimitiveType item = PrimitiveType.fromType(primitiveType);

        if (item == null) {
            schema = new ObjectSchema();
        } else {
            schema = item.createProperty();
        }

        // 获取schema的type和format
        String schemaType = schema.getType();
        String format = schema.getFormat();
        // 复制原schema的其它属性
        BeanUtils.copyProperties(sourceSchema, schema);

        // 使用根据枚举值类型获取到的schema
        return schema.type(schemaType).format(format);
    }
}
